package service

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"net/http"
	"os"
	"time"
	"weibo/pkg"
)

func OssUpload(c *gin.Context) {
	file, err := c.FormFile("image")
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"code": 400,
			"msg":  "接收文件失败",
		})
		return
	}
	if file.Size > 1024*1024*1 {
		c.JSON(http.StatusBadRequest, gin.H{
			"code": 400,
			"msg":  "图片大小不超过10MB",
		})
		return
	}
	filename := fmt.Sprintf("upload/%s/%s", time.Now().Format("20060102"), file.Filename)
	err = c.SaveUploadedFile(file, "./"+filename)
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"code": 400,
			"msg":  "本地图片上传失败",
		})
		return
	}
	wd, _ := os.Getwd()
	oss, err := pkg.Oss(wd, filename)
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"code": 400,
			"msg":  "OSS图片上传失败",
		})
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"code": 200,
		"msg":  "OSS图片上传成功",
		"data": gin.H{
			"url": oss,
		},
	})
	return
}
